/**
 * 数据存储模块
 * 负责所有数据的本地持久化存储和管理
 */
class DataStorage {
    constructor() {
        this.storageKey = 'mobile_cashier_data';
        this.products = [];
        this.orders = [];
        this.currentCart = [];
        
        // 加载存储的数据
        this.loadFromStorage();
        
        // 如果没有数据，初始化一些示例数据
        if (this.products.length === 0) {
            this._initSampleData();
        }
    }
    
    /**
     * 从localStorage或Android原生存储加载数据
     */
    loadFromStorage() {
        try {
            let jsonData = null;
            
            // 尝试从localStorage加载数据
            if (typeof localStorage !== 'undefined') {
                try {
                    jsonData = localStorage.getItem(this.storageKey);
                    if (jsonData) {
                        console.log('成功从localStorage加载数据');
                        const data = JSON.parse(jsonData);
                        this.products = data.products || [];
                        this.orders = data.orders || [];
                        this.currentCart = data.currentCart || [];
                        return;
                    }
                } catch (localStorageError) {
                    console.warn('从localStorage加载数据失败，尝试从Android原生存储加载:', localStorageError);
                }
            }
            
            // 如果localStorage没有数据或失败，尝试从Android原生存储加载
            if (typeof window.Android !== 'undefined' && typeof window.Android.loadData === 'function') {
                try {
                    jsonData = window.Android.loadData(this.storageKey);
                    if (jsonData && jsonData !== '') {
                        console.log('成功从Android原生存储加载数据');
                        const data = JSON.parse(jsonData);
                        this.products = data.products || [];
                        this.orders = data.orders || [];
                        this.currentCart = data.currentCart || [];
                        return;
                    }
                } catch (androidError) {
                    console.error('调用Android原生存储接口加载数据失败:', androidError);
                }
            }
            
            // 如果所有加载方式都失败，使用默认空数据
            console.log('没有找到已保存的数据，使用默认空数据');
        } catch (error) {
            console.error('加载数据过程中发生错误:', error);
            // 保持默认空数据
        }
    }

    /**
     * 初始化数据存储
     */
    init() {
        try {
            let data = localStorage.getItem(this.storageKey);
            if (data) {
                const parsedData = JSON.parse(data);
                this.products = parsedData.products || [];
                this.orders = parsedData.orders || [];
                this.currentCart = parsedData.currentCart || [];
            } else {
                // 初始化默认数据结构
                this.products = [];
                this.orders = [];
                this.currentCart = [];
                
                // 添加一些示例数据
                this._initSampleData();
            }
        } catch (error) {
            console.error('数据初始化失败:', error);
            // 初始化空数据结构作为备选方案
            this.products = [];
            this.orders = [];
            this.currentCart = [];
        }
    }

    /**
     * 初始化示例数据
     * @private
     */
    _initSampleData() {
        // 示例商品数据
        const sampleProducts = [
            { barcode: '1001', name: '矿泉水550ml', category: '饮料', cost: '1.00', price: '2.00', stock: 100 },
            { barcode: '1002', name: '可口可乐330ml', category: '饮料', cost: '2.00', price: '3.50', stock: 50 },
            { barcode: '1003', name: '巧克力蛋糕', category: '食品', cost: '8.00', price: '12.80', stock: 20 },
            { barcode: '1004', name: '面包', category: '食品', cost: '2.50', price: '4.50', stock: 30 },
            { barcode: '1005', name: '牛奶250ml', category: '饮料', cost: '3.00', price: '5.00', stock: 40 },
            { barcode: '1006', name: '薯片', category: '食品', cost: '4.00', price: '6.50', stock: 25 },
            { barcode: '1007', name: '水果糖', category: '食品', cost: '5.00', price: '8.00', stock: 15 },
            { barcode: '1008', name: '饼干', category: '食品', cost: '6.00', price: '9.90', stock: 35 }
        ];

        // 添加示例商品
        sampleProducts.forEach(product => {
            this.saveProduct(product);
        });

        // 示例订单数据
        const today = new Date();
        const yesterday = new Date();
        yesterday.setDate(today.getDate() - 1);
        
        const sampleOrders = [
            {
                id: 'ORD' + Date.now() + '01',
                date: today.toISOString(),
                items: [
                    { barcode: '1001', name: '矿泉水550ml', price: '2.00', quantity: 2 },
                    { barcode: '1003', name: '巧克力蛋糕', price: '12.80', quantity: 1 }
                ],
                totalAmount: '16.80'
            },
            {
                id: 'ORD' + Date.now() + '02',
                date: yesterday.toISOString(),
                items: [
                    { barcode: '1002', name: '可口可乐330ml', price: '3.50', quantity: 3 },
                    { barcode: '1006', name: '薯片', price: '6.50', quantity: 2 }
                ],
                totalAmount: '23.50'
            },
            {
                id: 'ORD' + Date.now() + '03',
                date: yesterday.toISOString(),
                items: [
                    { barcode: '1005', name: '牛奶250ml', price: '5.00', quantity: 4 },
                    { barcode: '1004', name: '面包', price: '4.50', quantity: 2 }
                ],
                totalAmount: '29.00'
            }
        ];

        // 添加示例订单
        sampleOrders.forEach(order => {
            this.orders.push(order);
        });

        // 保存示例数据
        this.saveToStorage();
    }

    /**
     * 将数据保存到localStorage或Android原生存储
     */
    saveToStorage() {
        try {
            const data = {
                products: this.products,
                orders: this.orders,
                currentCart: this.currentCart
            };
            const jsonData = JSON.stringify(data);
            
            // 尝试使用localStorage保存数据
            if (typeof localStorage !== 'undefined') {
                try {
                    // 测试localStorage写入权限
                    const testKey = 'localStorage-test';
                    localStorage.setItem(testKey, 'test-value');
                    localStorage.removeItem(testKey);
                    
                    localStorage.setItem(this.storageKey, jsonData);
                    console.log('数据成功保存到localStorage');
                    return true;
                } catch (localStorageError) {
                    console.warn('localStorage保存失败，尝试使用Android原生存储:', localStorageError);
                    // 继续尝试其他存储方式
                }
            } else {
                console.warn('localStorage不可用，尝试使用Android原生存储');
            }
            
            // 如果localStorage不可用或失败，尝试使用Android原生存储
            if (typeof window.Android !== 'undefined' && typeof window.Android.saveData === 'function') {
                try {
                    const result = window.Android.saveData(this.storageKey, jsonData);
                    if (result) {
                        console.log('数据成功保存到Android原生存储');
                        return true;
                    } else {
                        console.error('Android原生存储保存失败');
                    }
                } catch (androidError) {
                    console.error('调用Android原生存储接口失败:', androidError);
                }
            }
            
            // 所有存储方式都失败
            console.error('所有存储方式都失败，数据未保存');
            return false;
        } catch (error) {
            console.error('数据保存过程中发生错误:', error);
            // 提供更详细的错误类型信息
            if (error.name === 'QuotaExceededError') {
                console.error('localStorage存储空间不足');
            } else if (error.name === 'SecurityError') {
                console.error('localStorage安全限制错误，请检查WebView设置');
            }
            return false;
        }
    }

    /**
     * 查找商品
     * @param {string} barcode - 商品条形码
     * @returns {Object|null} 商品对象或null
     */
    findProduct(barcode) {
        return this.products.find(product => product.barcode === barcode) || null;
    }

    /**
     * 保存商品
     * @param {Object} product - 商品对象
     * @returns {boolean} 保存是否成功
     */
    saveProduct(product) {
        try {
            // 验证商品数据
            if (!product || !product.barcode || !product.name || !product.price) {
                throw new Error('商品信息不完整');
            }

            // 清理条形码数据，去除首尾空白字符并确保是字符串类型
            const cleanBarcode = String(product.barcode).trim();
            if (!cleanBarcode) {
                throw new Error('条形码不能为空');
            }

            // 验证价格格式
            const price = parseFloat(product.price);
            if (isNaN(price) || price < 0) {
                throw new Error('零售价格格式不正确');
            }

            // 验证进货价格式
            const cost = product.cost ? parseFloat(product.cost) : 0;
            if (isNaN(cost) || cost < 0) {
                throw new Error('进货价格格式不正确');
            }

            // 验证库存格式
            const stock = parseInt(product.stock) || 0;
            if (stock < 0) {
                throw new Error('库存数量不能为负数');
            }

            // 更新商品信息
            const existingIndex = this.products.findIndex(p => p.barcode === cleanBarcode);
            const updatedProduct = {
                barcode: cleanBarcode,
                name: product.name.trim(),
                category: product.category || '',
                cost: cost.toFixed(2),
                price: price.toFixed(2),
                stock: stock
            };

            if (existingIndex >= 0) {
                this.products[existingIndex] = updatedProduct;
            } else {
                this.products.push(updatedProduct);
            }

            return this.saveToStorage();
        } catch (error) {
            console.error('保存商品失败:', error);
            throw error;
        }
    }

    /**
     * 删除商品
     * @param {string} barcode - 商品条形码
     * @returns {boolean} 删除是否成功
     */
    deleteProduct(barcode) {
        const initialLength = this.products.length;
        this.products = this.products.filter(product => product.barcode !== barcode);
        
        // 如果商品被删除，从购物车中移除该商品
        this.currentCart = this.currentCart.filter(item => item.barcode !== barcode);
        
        return this.products.length !== initialLength && this.saveToStorage();
    }

    /**
     * 添加商品到购物车
     * @param {string} barcode - 商品条形码
     * @param {number} quantity - 数量
     * @returns {Object|null} 添加的商品或null
     */
    addToCart(barcode, quantity = 1) {
        const product = this.findProduct(barcode);
        if (!product) {
            return null;
        }

        // 检查库存
        if (product.stock < 1) {
            throw new Error('商品库存不足');
        }

        // 查找购物车中的商品
        const cartItemIndex = this.currentCart.findIndex(item => item.barcode === barcode);
        
        if (cartItemIndex >= 0) {
            // 检查是否超出库存
            if (product.stock < this.currentCart[cartItemIndex].quantity + quantity) {
                throw new Error('商品库存不足');
            }
            this.currentCart[cartItemIndex].quantity += quantity;
        } else {
            // 添加新商品到购物车
            this.currentCart.push({
                barcode: product.barcode,
                name: product.name,
                price: product.price,
                quantity: quantity
            });
        }

        this.saveToStorage();
        return product;
    }

    /**
     * 从购物车移除商品
     * @param {string} barcode - 商品条形码
     * @returns {boolean} 移除是否成功
     */
    removeFromCart(barcode) {
        const initialLength = this.currentCart.length;
        this.currentCart = this.currentCart.filter(item => item.barcode !== barcode);
        return this.currentCart.length !== initialLength && this.saveToStorage();
    }

    /**
     * 更新购物车商品数量
     * @param {string} barcode - 商品条形码
     * @param {number} quantity - 新数量
     * @returns {boolean} 更新是否成功
     */
    updateCartItemQuantity(barcode, quantity) {
        if (quantity < 1) {
            return this.removeFromCart(barcode);
        }

        const cartItemIndex = this.currentCart.findIndex(item => item.barcode === barcode);
        if (cartItemIndex === -1) {
            return false;
        }

        const product = this.findProduct(barcode);
        if (!product) {
            return false;
        }

        // 检查库存
        if (product.stock < quantity) {
            throw new Error('商品库存不足');
        }

        this.currentCart[cartItemIndex].quantity = quantity;
        return this.saveToStorage();
    }

    /**
     * 清空购物车
     * @returns {boolean} 清空是否成功
     */
    clearCart() {
        this.currentCart = [];
        return this.saveToStorage();
    }

    /**
     * 创建订单
     * @returns {Object|null} 创建的订单或null
     */
    createOrder() {
        if (this.currentCart.length === 0) {
            return null;
        }

        // 检查所有商品的库存
        for (const item of this.currentCart) {
            const product = this.findProduct(item.barcode);
            if (!product || product.stock < item.quantity) {
                throw new Error(`商品 "${item.name}" 库存不足`);
            }
        }

        // 计算订单总金额
        let totalAmount = 0;
        this.currentCart.forEach(item => {
            totalAmount += parseFloat(item.price) * item.quantity;
        });

        // 创建订单对象
        const order = {
            id: 'ORD' + Date.now(),
            date: new Date().toISOString(),
            items: JSON.parse(JSON.stringify(this.currentCart)),
            totalAmount: totalAmount.toFixed(2),
            // 添加订单状态，默认为待支付
            status: 'pending', // pending: 待支付, paid: 已支付, cancelled: 已取消
            paymentMethod: null, // 支付方式
            paymentTime: null // 支付时间
        };

        // 更新商品库存
        for (const item of this.currentCart) {
            const product = this.findProduct(item.barcode);
            if (product) {
                product.stock -= item.quantity;
            }
        }

        // 添加订单到订单列表
        this.orders.push(order);

        // 清空购物车
        this.currentCart = [];

        // 保存到存储
        this.saveToStorage();

        return order;
    }

    /**
     * 获取今日销售额
     * @returns {string} 今日销售额
     */
    getTodaySalesAmount() {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const todayTime = today.getTime();

        let totalAmount = 0;
        this.orders.forEach(order => {
            const orderDate = new Date(order.date);
            if (orderDate.getTime() >= todayTime) {
                totalAmount += parseFloat(order.totalAmount);
            }
        });

        return totalAmount.toFixed(2);
    }

    /**
     * 获取今日订单数
     * @returns {number} 今日订单数
     */
    getTodayOrderCount() {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const todayTime = today.getTime();

        let count = 0;
        this.orders.forEach(order => {
            const orderDate = new Date(order.date);
            if (orderDate.getTime() >= todayTime) {
                count++;
            }
        });

        return count;
    }

    /**
     * 获取库存预警商品列表
     * @param {number} threshold - 预警阈值
     * @returns {Array} 库存预警商品列表
     */
    getLowStockProducts(threshold = 10) {
        return this.products.filter(product => product.stock <= threshold);
    }

    /**
     * 导出商品数据为CSV
     * @returns {string} CSV格式的商品数据
     */
    exportProductsToCSV() {
        if (this.products.length === 0) {
            return '';
        }

        const headers = '条形码,商品名称,分类,进货价,零售价,库存\n';
        const rows = this.products.map(product => 
            `${product.barcode},${product.name},${product.category || ''},${product.cost || '0.00'},${product.price},${product.stock}`
        ).join('\n');

        return headers + rows;
    }

    /**
     * 导出订单数据为CSV
     * @returns {string} CSV格式的订单数据
     */
    exportOrdersToCSV() {
        if (this.orders.length === 0) {
            return '';
        }

        const headers = '订单ID,日期,总金额,商品明细\n';
        const rows = this.orders.map(order => {
            const itemsStr = order.items.map(item => 
                `${item.name}(${item.quantity}件)`
            ).join(';');
            return `${order.id},${order.date},${order.totalAmount},"${itemsStr}"`;
        }).join('\n');

        return headers + rows;
    }

    /**
     * 清除所有数据
     * @returns {boolean} 清除是否成功
     */
    clearAllData() {
        try {
            this.products = [];
            this.orders = [];
            this.currentCart = [];
            localStorage.removeItem(this.storageKey);
            return true;
        } catch (error) {
            console.error('清除数据失败:', error);
            return false;
        }
    }

    /**
     * 获取全部商品
     * @returns {Array} 商品列表
     */
    getAllProducts() {
        return this.products;
    }

    /**
     * 分页获取商品
     * @param {number} page - 页码（从1开始）
     * @param {number} pageSize - 每页数量
     * @param {string} keyword - 搜索关键词
     * @param {string} category - 商品分类
     * @returns {Object} 分页结果
     */
    getProductsByPage(page = 1, pageSize = 10, keyword = '', category = '') {
        let filteredProducts = this.products;
        
        // 分类过滤
        if (category) {
            filteredProducts = filteredProducts.filter(product => 
                product.category === category
            );
        }
        
        // 搜索过滤
        if (keyword) {
            const lowerKeyword = keyword.toLowerCase();
            filteredProducts = filteredProducts.filter(product => 
                product.name.toLowerCase().includes(lowerKeyword) || 
                product.barcode.includes(keyword)
            );
        }
        
        // 计算分页
        const total = filteredProducts.length;
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const items = filteredProducts.slice(startIndex, endIndex);
        const totalPages = Math.ceil(total / pageSize);
        
        return {
            items,
            total,
            totalPages,
            currentPage: page
        };
    }

    /**
     * 根据订单ID获取订单详情
     * @param {string} orderId - 订单ID
     * @returns {Object|null} 订单详情
     */
    getOrderById(orderId) {
        return this.orders.find(order => order.id === orderId) || null;
    }

    /**
     * 分页获取订单
     * @param {number} page - 页码（从1开始）
     * @param {number} pageSize - 每页数量
     * @param {string} status - 订单状态筛选 (all, pending, paid, cancelled)
     * @returns {Object} 分页结果
     */
    getOrdersByPage(page = 1, pageSize = 10, status = 'all') {
        // 筛选订单
        let filteredOrders = [...this.orders];
        if (status && status !== 'all') {
            filteredOrders = filteredOrders.filter(order => order.status === status);
        }
        
        // 按时间倒序排序
        const sortedOrders = filteredOrders.sort((a, b) => 
            new Date(b.date) - new Date(a.date)
        );
        
        // 计算分页
        const total = sortedOrders.length;
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const items = sortedOrders.slice(startIndex, endIndex);
        const totalPages = Math.ceil(total / pageSize);
        
        return {
            items,
            total,
            totalPages,
            currentPage: page,
            filterStatus: status
        };
    }

    /**
     * 获取购物车
     * @returns {Array} 购物车商品列表
     */
    getCart() {
        return this.currentCart;
    }

    /**
     * 获取订单列表
     * @returns {Array} 订单列表
     */
    getOrders() {
        return this.orders;
    }

    /**
     * 导入数据
     * @param {Object} data - 要导入的数据对象
     * @returns {boolean} 导入是否成功
     */
    importData(data) {
        try {
            if (data.products) {
                this.products = data.products;
            }
            if (data.orders) {
                this.orders = data.orders;
            }
            if (data.currentCart) {
                this.currentCart = data.currentCart;
            }
            return this.saveToStorage();
        } catch (error) {
            console.error('导入数据失败:', error);
            return false;
        }
    }

    /**
     * 备份数据
     * @returns {Object} 数据备份对象
     */
    backupData() {
        return {
            products: JSON.parse(JSON.stringify(this.products)),
            orders: JSON.parse(JSON.stringify(this.orders)),
            currentCart: JSON.parse(JSON.stringify(this.currentCart))
        };
    }

    /**
     * 恢复数据
     * @param {Object} backupData - 备份的数据对象
     * @returns {boolean} 恢复是否成功
     */
    restoreData(backupData) {
        try {
            if (!backupData) {
                throw new Error('备份数据无效');
            }
            
            this.products = backupData.products || [];
            this.orders = backupData.orders || [];
            this.currentCart = backupData.currentCart || [];
            
            return this.saveToStorage();
        } catch (error) {
            console.error('恢复数据失败:', error);
            return false;
        }
    }

    /**
     * 更新订单状态
     * @param {string} orderId - 订单ID
     * @param {string} status - 新状态 (pending, paid, cancelled)
     * @param {string} paymentSource - 支付来源
     * @returns {boolean} 更新是否成功
     */
    updateOrderStatus(orderId, status, paymentSource = null) {
        const order = this.orders.find(o => o.id === orderId);
        if (!order) {
            return false;
        }

        order.status = status;
        if (status === 'paid') {
            order.paymentTime = new Date().toISOString();
            
            // 根据支付来源设置支付方式
            if (paymentSource === 'manual') {
                order.paymentMethod = 'manual'; // 手动确认支付
            } else if (paymentSource) {
                order.paymentMethod = paymentSource; // 使用支付来源作为支付方式
            } else {
                order.paymentMethod = order.paymentMethod || 'unknown'; // 保留原有支付方式或默认值
            }
            
            // 记录支付来源
            order.paymentSource = paymentSource || 'unknown';
        }
        
        // 保存到存储
        return this.saveToStorage();
    }
}

// 创建DataStorage实例并暴露到全局window对象
if (typeof window !== 'undefined') {
    window.dataStore = new DataStorage();
}